//
//  ANWebService.m
//  Ants
//
//  Created by ZHM on 16/4/24.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANWebService.h"
#import <CoreLocation/CoreLocation.h>
#import "ANShoppingCarCellFrame.h"

@implementation ANWebService
//+ (ANWebService *)sharedInstance {
//    DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
//        return [ANWebService new];
//    });
//}

+ (ANWebService *)sharedInstance {
    static ANWebService *serveice = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        serveice = [[self.class alloc] init];
    });
    return serveice;
}
- (NSMutableArray *)shoppingItems {
    if (!_shoppingItems) {
        _shoppingItems = [NSMutableArray array];
        if (![sharedWebService isLoggedIn]) {
            return nil;
        }
        [self fetchCurrentUserShoppingItemsCompletion:^(NSArray *shoppingItems, NSError *error) {
            if (!error && shoppingItems.count) {
                NSMutableArray *itemFrams = [NSMutableArray array];
                for (ANBDShoppingItem *item in shoppingItems) {
                    ANShoppingCarCellFrame *cellFrame = [[ANShoppingCarCellFrame alloc] init];
                    cellFrame.shoppingItem = item;
                    [itemFrams addObject:cellFrame];
                }
                [_shoppingItems addObjectsFromArray:itemFrams];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshShoppingCar" object:nil];
            }
        }];
    }
    return _shoppingItems;
}

- (id)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    //默认的上下文操作会在在主线程中进行
    _defaultContext = [NSManagedObjectContext MR_defaultContext];
    
    _sharedContext = [NSManagedObjectContext MR_newMainQueueContext];
    [_sharedContext setPersistentStoreCoordinator:[NSPersistentStoreCoordinator MR_defaultStoreCoordinator]];
    return self;
}


- (ANBDProductCategory *)productCategoryFormBmobObject:(BmobObject *)productCategoryObject {
    NSString *categoryName = [productCategoryObject objectForKey:@"title"];
    ANBDProductCategory *productCategory = [ANBDProductCategory MR_findFirstOrCreateByAttribute:@"title" withValue:categoryName inContext:self.sharedContext];
    productCategory.iconUrlString = [productCategoryObject objectForKey:@"iconUrlString"];
    productCategory.title = categoryName;
    productCategory.bmObject = productCategoryObject;
    [self.sharedContext MR_saveToPersistentStoreAndWait];
    return productCategory;
}


//转换
- (BmobObject *)bmobObject:(BmobObject *)productObject FormProduct:(ANBDProduct *)product {
    
    [productObject setObject:product.title forKey:@"title"];
    [productObject setObject:product.intro forKey:@"intro"];
    CLLocation *location = product.location;
    BmobGeoPoint *point = [[BmobGeoPoint alloc] initWithLongitude:location.coordinate.longitude WithLatitude:location.coordinate.latitude];
    [productObject setObject:point forKey:@"location"];
    [productObject setObject:product.services forKey:@"services"];
    [productObject setObject:product.icons forKey:@"icons"];
    [productObject setObject:product.price forKey:@"price"];
    [productObject setObject:product.originalPrice forKey:@"originalPrice"];
    [productObject setObject:product.quantity forKey:@"quantity"];
    [productObject setObject:product.address forKey:@"address"];
    
    return productObject;
}

- (ANBDShoppingItem *)shoppingItemFromBmobObject:(BmobObject *)object {
    BmobObject *productObject = [object objectForKey:@"product"];
    ANBDProduct *product = [self productFormBmobObject:productObject];

    ANBDShoppingItem *item = [ANBDShoppingItem MR_findFirstOrCreateByAttribute:@"product" withValue:product inContext:self.sharedContext];
    item.quantity = [object objectForKey:@"quantity"];
    item.createdAt = object.createdAt;
    item.custom_infos = [object objectForKey:@"custom_infos"];
    item.mlObjectId = object.objectId;
    item.selected_custom_info1 = [object objectForKey:@"custom_info1"];
    item.selected_custom_info2 = [object objectForKey:@"custom_info2"];
    item.selected_custom_info3 = [object objectForKey:@"custom_info3"];
    item.bmObject = object;
    return item;
}
//转换
- (ANBDProduct *)productFormBmobObject:(BmobObject *)productObject {
    NSString *mlObjectId = productObject.objectId;
    ANBDProduct *product = [ANBDProduct MR_findFirstOrCreateByAttribute:@"mlObjectId" withValue:mlObjectId inContext:self.sharedContext];
    product.mlObjectId = productObject.objectId;
    product.title = [productObject objectForKey:@"title"];
    product.bmObject = productObject;
    product.price = [NSDecimalNumber decimalNumberWithDecimal:[[productObject objectForKey:@"price"] decimalValue]];
    product.originalPrice = [NSDecimalNumber decimalNumberWithDecimal:[[productObject objectForKey:@"originalPrice"] decimalValue]];
    product.quantity = [productObject objectForKey:@"quantity"];
    product.intro = [productObject objectForKey:@"intro"];
    product.icons = [productObject objectForKey:@"icons"];
    product.services = [productObject objectForKey:@"services"];
    product.address = [productObject objectForKey:@"address"];
    product.info = [productObject objectForKey:@"info"];
    product.custom_info1 = [productObject objectForKey:@"custom_info1"];
    product.custom_info2 = [productObject objectForKey:@"custom_info2"];
    product.custom_info3 = [productObject objectForKey:@"custom_info3"];
    product.createdAt = productObject.createdAt;
    
    BmobGeoPoint *point = [productObject objectForKey:@"location"];
    product.location = [[CLLocation alloc] initWithLatitude:point.latitude longitude:point.longitude];
    
    BmobObject *categoryObject = [productObject objectForKey:@"category"];
    if (!categoryObject.createdAt) {
        BmobObject *objectId = [productObject objectForKey:@"category"];
        for (ANBDProductCategory *oneCategory in _categorys) {
            BmobObject *categoryObjectOne = (BmobObject *)oneCategory.bmObject;
            if ([objectId.objectId isEqualToString:categoryObjectOne.objectId]) {
                //ANLog(@"找到:%@",oneCategory.bmObject);
                product.category = oneCategory;
            }
        }
    } else {
        product.category = [self productCategoryFormBmobObject:categoryObject];
    }
    
    
    //ANLog(@"category:%@",[productObject objectForKey:@"category"]);
    
    
    [self.sharedContext MR_saveToPersistentStoreWithCompletion:nil];
    
    return product;
}

@end
